import React from 'react'

// 引入地区的数据
import {areaList} from '@vant/area-data'

const Add = () =>
{
    // 初始化路由跳转对象
    const navigate = React.$Router.useNavigate()

    // 获取传过来的商品
    const [searchParams] = React.$Router.useSearchParams()
    const [proid,setProid] = React.useState(searchParams.get('proid'))

    // 初始化状态
    const [LoginUser,setLoginUser] = React.useState(React.$LoginUser)
    const [product,setProduct] = React.useState({})

    // 地区
    const [RegionShow, SetRegionShow] = React.useState(false)
    const [region, SetRegion] = React.useState('')
    const [code, SetCode] = React.useState([])

    React.useEffect(() => {
        let LoginUser = React.$Cookie.load('LoginUser',{path:'/'}) ? JSON.parse(React.$Cookie.load('LoginUser',{path:'/'})) : {}
        let product = React.$Cookie.load('product') ? React.$Cookie.load('product') : {}

        setLoginUser(LoginUser)

        setProduct(product)

        RegionInit()

        Total()
    },[])

    // 初始化地区数据
    const RegionInit  = () =>
    {
        let region_text = ''
        let region_code = []

        if(LoginUser.province)
        {
            region_text = LoginUser.province_text + '-'
            region_code.push(LoginUser.province)
        }

        if(LoginUser.city)
        {
            region_text += LoginUser.city_text + '-'
            region_code.push(LoginUser.city)
        }

        if(LoginUser.district)
        {
            region_text += LoginUser.district_text
            region_code.push(LoginUser.district)
        }

        SetRegionShow(false)

        SetRegion(region_text)
        SetCode(region_code)
    }

    const RegionConfirm = (_,e) =>
    {
        let [province,city,district] = e

        if(province)
        {
            LoginUser.province_text = province.text

            LoginUser.province = province.value
        }

        if(city)
        {
            LoginUser.city_text = city.text

            LoginUser.city = city.value
        }

        if(district)
        {
            LoginUser.district_text = district.text

            LoginUser.district = district.value
        }

        RegionInit()
    }

    // 日期
    const [DateShow, SetDateShow] = React.useState(false)

    //10天后的日期
    const [end, SetEnd] = React.useState(new Date(new Date().getTime() + 10*24*60*60*1000))
    const [day, SetDay] = React.useState(10)
    const [endtime, SetEndTime] = React.useState(`${end.getFullYear()}-${end.getMonth() + 1}-${end.getDate()}`)

    // 选择日期
    const DateConfirm = (date) =>
    {
        SetEndTime(`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`)

        SetDateShow(false)

        SetEnd(date)

        Total()
    }

    // 图片
    const [card, SetCard] = React.useState([])

    // 价格

    //不含押金
    const [price, SetPrice] = React.useState(0)

    // 含押金
    const [rent, SetRent] = React.useState(0)

    // 计算总价
    const Total = () =>
    {
        let product = React.$Cookie.load('product') ? React.$Cookie.load('product') : {}

        // 日供
        let RentPrice = product.rent_price ? parseFloat(product.rent_price) : 0

        // 押金
        let rent = product.rent ? parseFloat(product.rent) : 0

        // 获取当前时间
        let now = new Date()

        let time = end - now

        let days = Math.ceil(time / (1000 * 60 * 60 *24))

        SetDay(days)

        let price = parseFloat(RentPrice * days)
        price = price.toFixed(2)

        SetPrice(price)

        let Rent = parseFloat(price) + rent

        SetRent(Rent)
    }

    // 表单内容
    const [form] = React.$Vant.Form.useForm()

    // 提交表单数据
    const onAdd = async (form) =>
    {

        let data = {
            busid:LoginUser.id,
            proid:product.id,
            endtime:endtime,
            day:day,
            address:form.address,
            province:LoginUser.province,
            city:LoginUser.city,
            district:LoginUser.district
        }

        // 判断是否上传证件
        if(form.card.length > 0 && form.card[0].file)
        {
            data.card = form.card[0].file
        }

        let result = await React.$Api.LeaseAdd(data)

        if(result.code === 1)
        {
            
            React.$Vant.Notify.show({
                type:'success',
                message:result.msg,
                onClose:() => {

                    React.$Cookie.remove('product')

                    navigate('/lease/lease/index')
                }
            })

            return false
        }else{
            React.$Vant.Notify.show({
                type:'warning',
                message:result.msg
            })

            return false
        }
    }

    // 选择商品
    const SelectProduct = () =>
    {
        navigate('/product/product/index?action=add')
    }

    const onBack = () =>
    {
        React.$Cookie.remove('product')
        navigate(-1)
    }

    return (
        <>
            {/* 导航栏 */}
            <React.$Vant.Sticky>
                <React.$Vant.NavBar 
                    title='立即租赁'
                    onClickLeft={onBack}
                />
            </React.$Vant.Sticky>

            <div className='add'>
                <React.$Vant.Form form={form} onFinish={onAdd}>
                    {/* 选择租赁商品 */}
                    <React.$Vant.Form.Item
                        labelWidth='4em'
                        labelAlign='right'
                        label="租赁商品"
                        onClick={SelectProduct}
                    >
                        <React.$Vant.Input placeholder="租赁商品" isLink readonly value={product.name ? product.name : ''} />
                    </React.$Vant.Form.Item>

                    <React.$Vant.Form.Item
                        label="押金"
                        labelWidth='4em'
                        labelAlign='right'
                    >
                        <React.$Vant.Input readonly value={product.rent ? product.rent : ''} />
                    </React.$Vant.Form.Item>

                    <React.$Vant.Form.Item
                        label="日供"
                        labelWidth='4em'
                        labelAlign='right'
                    >
                        <React.$Vant.Input readonly value={product.rent_price ? product.rent_price : ''} />
                    </React.$Vant.Form.Item>

                    <br />
                    <br />

                    <React.$Vant.Form.Item
                        name="nickname"
                        label="昵称"
                        labelWidth='4em'
                        labelAlign='right'
                        initialValue={LoginUser.nickname}
                        rules={[
                            { required: true, message: '请输入昵称' }
                        ]}
                    >
                        <React.$Vant.Input placeholder="请输入昵称" />
                    </React.$Vant.Form.Item>

                    <React.$Vant.Form.Item
                        label="手机号"
                        name="mobile"
                        labelWidth='4em'
                        labelAlign='right'
                        initialValue={LoginUser.mobile}
                        rules={[
                            { required: true, message: '请输入手机号' }
                        ]}
                    >
                        <React.$Vant.Input placeholder="请输入手机号" />
                    </React.$Vant.Form.Item>

                    {/* 地区 */}
                    <React.$Vant.Form.Item
                        label="地区"
                        labelWidth='4em'
                        labelAlign='right'
                        onClick={() => { SetRegionShow(true) }}
                    >
                        <React.$Vant.Input placeholder="请选择地区" isLink readonly value={region} />
                    </React.$Vant.Form.Item>

                    <React.$Vant.Popup position="bottom" round visible={RegionShow} onClose={() => { SetRegionShow(false) }}>
                        <React.$Vant.Area
                            title="请选择地区"
                            areaList={areaList}
                            value={code}
                            onCancel={() => { SetRegionShow(false) }}
                            onConfirm={RegionConfirm}
                        />
                    </React.$Vant.Popup>

                    <React.$Vant.Form.Item
                        name="address"
                        label="详细地址"
                        labelWidth='4em'
                        labelAlign='right'
                        rules={[
                            { required: true, message: '请输入详细地址' }
                        ]}
                    >
                        <React.$Vant.Input placeholder="请输入详细地址" />
                    </React.$Vant.Form.Item>

                    <React.$Vant.Form.Item
                        label="租用时间"
                        labelWidth='4em'
                        labelAlign='right'
                        onClick={() => { SetDateShow(true) }}
                    >
                        <React.$Vant.Input isLink readonly value={endtime} />
                    </React.$Vant.Form.Item>

                    <React.$Vant.Calendar
                        showConfirm={false}
                        visible={DateShow}
                        defaultDate={end}
                        onClose={() => { SetDateShow(false) }}
                        onConfirm={DateConfirm}
                    />

                    {/* 图片 */}
                    <React.$Vant.Form.Item
                        label="上传证件"
                        name="card"
                        labelWidth='4em'
                        labelAlign='right'
                        rules={[
                            { required: true, message: '请上传证件图片' }
                        ]}
                    >
                        <React.$Vant.Uploader previewSize={150} maxCount={1} value={card} />
                    </React.$Vant.Form.Item>

                    <div className="zy_goods_foot dis_flex">
                        <div className="left">
                            <div>{day}天<b>￥<em>{price}</em></b></div>
                            <div className="tou_d">含押金￥{rent}</div>
                        </div>
                        <p>
                            <React.$Vant.Button nativeType="submit" block size="normal" type="primary">立即申请</React.$Vant.Button>
                        </p>
                    </div>
                </React.$Vant.Form>
            </div>
        </>
    )
}

export default Add